import React, { useCallback, useState, useEffect } from "react";
import { useDispatch } from "react-redux";
import Notice from "../Share/NotFound";
import { useHistory, useLocation } from "react-router";
import API from "../../middleware/Api";
import Auth from "../../middleware/Auth";
import { applyThemes, setSessionStatus, toggleSnackbar } from "../../redux/explorer";

function useQuery() {
    return new URLSearchParams(useLocation().search);
}

export default function QQCallback() {
    const query = useQuery();
    const location = useLocation();
    const history = useHistory();
    const dispatch = useDispatch();
    const ToggleSnackbar = useCallback(
        (vertical, horizontal, msg, color) =>
            dispatch(toggleSnackbar(vertical, horizontal, msg, color)),
        [dispatch]
    );
    const ApplyThemes = useCallback((theme) => dispatch(applyThemes(theme)), [
        dispatch,
    ]);
    const SetSessionStatus = useCallback(
        (status) => dispatch(setSessionStatus(status)),
        [dispatch]
    );

    const [msg, setMsg] = useState("");

    const getCookie =(name)=> {
        const strcookie = document.cookie;//获取cookie字符串
            const arrcookie = strcookie.split("; ");//分割
            //遍历匹配
            for ( let i = 0; i < arrcookie.length; i++) {
                const arr = arrcookie[i].split("=");
                if (arr[0] == name){
                    return unescape(arr[1]);
                }
            }
        return null;
    }

    const GetQueryString =(name)=> {
        const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i"); 
        const r = window.location.search.substr(1).match(reg); 
        if (r!=null) return (r[2]); return ""; 
    }
    
    const afterLogin = (data) => {
        Auth.authenticate(data);

        // 设置用户主题色
        if (data["preferred_theme"] !== "") {
            ApplyThemes(data["preferred_theme"]);
        }

        // 设置登录状态
        SetSessionStatus(true);
        const backurl = GetQueryString("backurl");
        if (backurl==""){
            history.push("/home");
        }else{
            const backurl_path = backurl.split(".");
            if (backurl_path[1]!="bilnn"){
                history.push("/home");
            }else{
                window.location.href = decodeURIComponent(backurl)+"?token="+getCookie("token");
            } 
        }
        ToggleSnackbar("top", "right", "登录成功", "success");

        localStorage.removeItem("siteConfigCache");
    };

    useEffect(() => {
        if (query.get("error_description")) {
            setMsg(query.get("error_description"));
            return;
        }
        if (query.get("code") === null) {
            return;
        }
        API.post("/callback/qq", {
            code: query.get("code"),
            state: query.get("state"),
        })
            .then((response) => {
                if (response.rawData.code === 203) {
                    afterLogin(response.data);
                } else {
                    history.push(response.data);
                }
            })
            .catch((error) => {
                setMsg(error.message);
            });
        // eslint-disable-next-line
    }, [location]);

    return <>{msg !== "" && <Notice msg={msg} />}</>;
}
